using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Forms;
using System.Drawing;
using Tools;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Animation;
using System.Diagnostics;

namespace BingAuto
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // 定义导航类型枚举
        private enum NavigationType
        {
            PreviousDay, // 前一天
            NextDay,     // 后一天
            Today        // 今天
        }
        string appName =  System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();

        BingServer bingServer = new BingServer();
        
        // 当前浏览的图片日期
        private DateTime currentBrowseDate = DateTime.Now;
        
        // 当前显示的图片记录
        private BingServer.GetImageEventArgs currentImageRecord = null;
        
        // 状态显示图标
        private System.Windows.Controls.Image imageStatus;
        
        public MainWindow()
        {
            if (Utils.IsAppOpened(appName))
            {
                Logger.Info("程序启动", "检测到程序已在运行，退出新实例");
                System.Environment.Exit(0);
            }
            
            InitializeComponent();

            //检查开机自启
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            if(Utils.IsAutoStart(path,appName))
                CheckBox_Power.IsChecked = true;

            // 初始化状态图标
            imageStatus = this.FindName("Image_Status") as System.Windows.Controls.Image;

            // 注册事件处理程序
            bingServer.GetImageEvent += GetBingHandler;
            bingServer.StatusChangedEvent += ServerStatusChangedHandler;
            
            // 启动图片服务器
            bingServer.Start();
            
            // 初始化更新按钮状态
            UpdateButtonStates();

            Utils.InitializeTray(NotifyIcon_MouseDoubleClick,Open_Click,Exit_Click);
        }
        
        // 更新按钮状态
        private void UpdateButtonStates()
        {
            BtnPrevious.IsEnabled = true; // 始终允许查看前一天
            
            // 当前日期为今天时，不显示下一天按钮
            if (currentBrowseDate.Date == DateTime.Now.Date)
            {
                BtnNext.IsEnabled = false;
            }
            else
            {
                BtnNext.IsEnabled = true;
            }
        }
        
        // 通用的日期切换方法
        private void NavigateDate(NavigationType navigationType)
        {
            string navigationTypeStr = navigationType.ToString();
            
            // 根据导航类型执行不同的日期切换逻辑
            switch (navigationType)
            {
                case NavigationType.PreviousDay:
                    // 直接导航到前一天
                    currentBrowseDate = currentBrowseDate.AddDays(-1);
                    break;
                
                case NavigationType.NextDay:
                    // 直接导航到后一天
                    if(currentBrowseDate.Date < DateTime.Now.Date)
                    {
                        currentBrowseDate = currentBrowseDate.AddDays(1);
                    }
                    break;
                
                case NavigationType.Today:
                    // 直接导航到今天
                    currentBrowseDate = DateTime.Now;
                    break;
            }
            
            // 尝试查找该日期的记录
            currentImageRecord = bingServer.GetBingImageRecord(currentBrowseDate);
            
            // 显示该日期（无论是否有记录）
            ShowDate(currentBrowseDate);
            
            // 根据是否有记录更新UI
            if (currentImageRecord == null)
            {
                Logger.Warning("日期导航", $"{currentBrowseDate.ToString("yyyyMMdd")}图片无记录，尝试获取...");
                // 清除当前显示
                Label_Title.Content = "加载中";
                Label_Copyright.Content = "正在加载壁纸...";
                Image_Bing.Source = null;
                // 当前日期与浏览日期相同且服务器状态为正在获取图片时，避免重复发起网络请求获取图片
                if (currentBrowseDate.Date != DateTime.Now.Date
                || bingServer.CurrentStatus != BingServer.ServerStatus.GettingImage)
                {
                    // 无记录：尝试通过API获取该日期的图片
                    Task.Run(async () => 
                    {
                        try
                        {
                            bool success = await bingServer.GetBingImage(currentBrowseDate);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException("图片获取", ex);
                        }
                    });
                }
            }
            else if (!File.Exists(currentImageRecord.filePath))
            {
                Logger.Warning("日期导航", $"{currentBrowseDate.ToString("yyyyMMdd")}图片文件不存在: {currentImageRecord.filePath}，尝试重新获取...");
                // 清除当前显示
                Label_Title.Content = "加载中";
                Label_Copyright.Content = "壁纸丢失，正在重新获取...";
                Image_Bing.Source = null;
                Task.Run(async () => 
                {
                    try
                    {
                        bool success = await bingServer.GetBingImage(currentImageRecord);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException("图片获取", ex);
                    }
                });
            }
            else
            {
                //Logger.Info("日期导航", $"{currentBrowseDate.ToString("yyyyMMdd")}图片已存在，直接加载...");
                UpdateUI(currentImageRecord);
            }
            // 更新按钮状态
            UpdateButtonStates();
        }
        
        // 上一张按钮点击事件（查看前一天）
        private void BtnPrevious_Click(object sender, RoutedEventArgs e)
        {
            NavigateDate(NavigationType.PreviousDay);
        }
        
        private void BtnNext_Click(object sender, RoutedEventArgs e)
        {
            NavigateDate(NavigationType.NextDay);
        }
        
        // 返回今天按钮点击事件
        private void BtnToday_Click(object sender, RoutedEventArgs e)
        {
            if (currentBrowseDate.Date != DateTime.Now.Date ||
                bingServer.CurrentStatus == BingServer.ServerStatus.WaitingRetry)
            {
                NavigateDate(NavigationType.Today);
            }
        }
        void GetBingHandler(object sender, BingServer.GetImageEventArgs args)
        {
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                //更新UI代码
                UpdateUI(args);
            }));
        }
        
        // 服务器状态变更事件处理程序
        void ServerStatusChangedHandler(object sender, BingServer.ServerStatus status)
        {
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                if (imageStatus != null)
                {
                    // 获取动画资源
                    Storyboard loaderAnimation = (Storyboard)FindResource("LoaderAnimation");
                    
                    // 根据状态更新显示图标和提示
                    switch (status)
                    {
                        case BingServer.ServerStatus.WaitingRetry:
                            imageStatus.Source = (System.Windows.Media.DrawingImage)FindResource("droplet_orange_DrawingImage");
                            imageStatus.ToolTip = "服务状态: 异常，等待重试...";
                            // 停止动画并清除目标
                            loaderAnimation.Stop();
                            Storyboard.SetTarget(loaderAnimation, null);
                            break;
                        case BingServer.ServerStatus.GettingImage:
                            imageStatus.Source = (System.Windows.Media.DrawingImage)FindResource("loaderDrawingImage");
                            imageStatus.ToolTip = "服务状态: 正在获取...";
                            // 停止之前的动画，设置新目标并启动
                            loaderAnimation.Stop();
                            Storyboard.SetTarget(loaderAnimation, imageStatus);
                            loaderAnimation.Begin();
                            break;
                        case BingServer.ServerStatus.Sleeping:
                            imageStatus.Source = (System.Windows.Media.DrawingImage)FindResource("droplet_green_DrawingImage");
                            imageStatus.ToolTip = "服务状态: 今日已获取成功，休眠中...";
                            // 停止动画并清除目标
                            loaderAnimation.Stop();
                            Storyboard.SetTarget(loaderAnimation, null);
                            break;
                        default:
                            break;
                    }
                }
            }));
        }
        void UpdateUI(BingServer.GetImageEventArgs args)
        {
            // 由Server请求导航到新的一天
            if(args.title == "GoToToday")
            {
                currentBrowseDate = DateTime.Now;
                ShowDate(currentBrowseDate);
                // 清除当前显示
                Label_Title.Content = "加载中";
                Label_Copyright.Content = "正在加载壁纸...";
                Image_Bing.Source = null;
            }
            // 如果收到了新的信息，并且“获取的日期为当前正在浏览日期”或“获取的日期为今日日期且当前浏览的为已获取到的最新日期”，则更新UI
            // 否则不更新UI，保持当前浏览的历史图片不变
            else if ((!string.IsNullOrEmpty(args.updateDate) && currentBrowseDate.ToString("yyyyMMdd") == args.updateDate)
                || (BtnNext.IsEnabled == false && args.updateDate == DateTime.Now.ToString("yyyyMMdd")))
            {
                Label_Title.Content = args.title;
                Label_Copyright.Content = args.copyright.Replace("?", "©");
                if (args.title != "Error")
                {
                    // 保存旧的图片资源引用，以便稍后释放
                    var oldImageSource = Image_Bing.Source;
                    
                    // 加载新的图片资源
                    if (File.Exists(args.filePath))
                        Image_Bing.Source = Utils.LoadImage(args.filePath);
                    else if (args.imageUrl != "" && oldImageSource == null)
                    {
                        Image_Bing.Source = Utils.LoadImage(args.imageUrl);
                    }
                    
                    // 尝试释放旧的图片资源
                    if (oldImageSource != null && oldImageSource != Image_Bing.Source)
                    {
                        // 强制垃圾回收，释放未引用的图片资源
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }
                }
            }
        }


        #region 托盘事件处理
        //打开事件处理
        private void Open_Click(object sender, EventArgs e)
        {
            this.Visibility = Visibility.Visible;
            this.Activate();
        }
        
        // 退出事件处理
        private void Exit_Click(object sender, EventArgs e)
        {
            //if (System.Windows.MessageBox.Show("退出将不能再自动更换壁纸，确定退出吗?",
            //                                   "BingAuto by Talon",
            //                                    MessageBoxButton.YesNo,
            //                                    MessageBoxImage.Question,
            //                                    MessageBoxResult.Yes) == MessageBoxResult.Yes)
            {
                //System.Windows.Application.Current.Shutdown();
                bingServer.Stop(); 
                System.Environment.Exit(0);
            }
        }
        //单击事件处理
        private void NotifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.Visibility == Visibility.Visible)
                {
                    this.Visibility = Visibility.Hidden;
                }
                else
                {
                    this.Visibility = Visibility.Visible;
                    this.Activate();
                }
            }
        }
        #endregion

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            string path= Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            string startPath = AppDomain.CurrentDomain.BaseDirectory.ToString();

            Utils.CreateAutoStart(path, appName, startPath + appName + ".exe");
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            Utils.DeleteAutoStart(path, appName);
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Visibility = Visibility.Hidden;
        }

        // 设置壁纸按钮点击事件
        private void BtnSetWallpaper_Click(object sender, RoutedEventArgs e)
        {
            if (currentImageRecord != null && File.Exists(currentImageRecord.filePath))
            {
                // 如果正在浏览特定日期的图片，则设置当前显示的图片为壁纸
                int result = Utils.SetDesktopImage(currentImageRecord.filePath);
                Logger.Info("壁纸设置", $"设置壁纸: {currentImageRecord.title} 文件: {currentImageRecord.filePath}, 结果码: {result}");
            }
            else
            {
                Logger.Warning("壁纸设置", "无法设置壁纸：当前无有效图片记录或图片文件不存在");
            }
        }
        
        // 显示指定日期
        private void ShowDate(DateTime date)
        {
            string formattedDate = String.Format("{0}年{1}月{2}日", date.Year, date.Month, date.Day);
            Label_Date.Content = formattedDate;
        }
    }
}
